package com.usts.englishlearning.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;

import com.bumptech.glide.Glide;
import com.usts.englishlearning.R;
import com.usts.englishlearning.activity.service.NotifyLearnService;
import com.usts.englishlearning.config.ConfigData;
import com.usts.englishlearning.database.DailyData;
import com.usts.englishlearning.database.UserConfig;
import com.usts.englishlearning.model.PermissionListener;
import com.usts.englishlearning.util.ActivityCollector;
import com.usts.englishlearning.util.BaiduHelper;
import com.usts.englishlearning.util.MyApplication;
import com.usts.englishlearning.util.TimeController;

import org.litepal.LitePal;

import java.util.List;


public class WelcomeActivity extends BaseActivity {

    private static final String TAG = "WelcomeActivity";
    private final int FINISH = 1;
    // 壁纸
    private ImageView imgBackground;
    // 每日一句卡片
    private CardView cardWelCome;
    // 每日一句文字
    private TextView textWelCome;
    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case FINISH:
//                    设置壁纸
                    List<DailyData> dailyDataList = LitePal.where("dayTime = ?", TimeController.getCurrentDateStamp() + "").find(DailyData.class);
                    if (!dailyDataList.isEmpty()) {
                        DailyData dailyData = dailyDataList.get(0);
                        textWelCome.setText(dailyData.getDailyEn());
                        Glide.with(WelcomeActivity.this).load(dailyData.getPicVertical()).into(imgBackground);
                    }
                    break;
            }
        }
    };
    // 缩放动画
    private ScaleAnimation animation;
    private String rootPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        rootPath = Environment.getDataDirectory().getPath();
        Log.d(TAG, "路径" + rootPath);

        // 防止重复
        //  问题描述：
        // 应用安装后，通过安装界面的打开按钮打开应用，每当应用从后台切换到前台，都会启动欢迎界面。如果是通过点击应用启动，则没有此问题。
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            ActivityCollector.removeActivity(this);
            finish();
            return;
        }

        init();

        // 设置透明度
        cardWelCome.getBackground().setAlpha(200);

        // 设置数据显示
        new Thread(new Runnable() {
            @Override
            public void run() {
//                请求必应壁纸数据
                prepareDailyData();
                Message message = new Message();
                message.what = FINISH;
                handler.sendMessage(message);
//                拍照取词用百度api
                BaiduHelper.getAssessToken();
            }
        }).start();

        // 如果不是第一次运行
        if (!ConfigData.getIsFirst()) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    imgBackground.startAnimation(animation);
                }
            }, 500);
            // 设置学习提醒
            if (ConfigData.getIsAlarm()) {
                int hour = Integer.parseInt(ConfigData.getAlarmTime().split("-")[0]);
                int minute = Integer.parseInt(ConfigData.getAlarmTime().split("-")[1]);
                AlarmActivity.startAlarm(hour, minute, false, false);
            }
            // 设置通知栏单词
            if (ConfigData.getIsNotifyLearn()) {
                if (!BaseActivity.isServiceExisted(MyApplication.getContext(), NotifyLearnService.class.getName())) {
                    // 检查当前是否数据有效
                    LearnInNotifyActivity.checkIsAvailable();
                    LearnInNotifyActivity.startService(ConfigData.getNotifyLearnMode());
                }
            }
        }

        MainActivity.lastFragment = 0;

    }

    private void init() {

        cardWelCome = findViewById(R.id.card_wel1);
        textWelCome = findViewById(R.id.text_wel);
        imgBackground = findViewById(R.id.img_wel_bg);

        animationConfig();
        requestPermission();
    }


    // 权限管理
    private void requestPermission() {
        requestRunPermission(ConfigData.permissions, new PermissionListener() {
            @Override
            public void onGranted() {

                // 设置第一次运行的值为否
                ConfigData.setIsFirst(false);
                // 延迟时间再开始动画
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        imgBackground.startAnimation(animation);
                    }
                }, 600);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {// android 11  且 不是已经被拒绝
                    // 先判断有没有权限 跳到系统赋予所有权限界面 清单文件中需要加入
                    //<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
                    if (!Environment.isExternalStorageManager()) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivityForResult(intent, 1024);
                    }

                }
            }

            @Override
            public void onDenied(List<String> deniedPermission) {
                if (!deniedPermission.isEmpty()) {
                    Toast.makeText(WelcomeActivity.this, "无法获得权限，程序即将退出", Toast.LENGTH_SHORT).show();
                    ActivityCollector.finishAll();
                }
            }
        });
    }

    // 缩放动画配置
    private void animationConfig() {
        // 从原图大小，放大到1.5倍
        animation = new ScaleAnimation(1, 1.5f, 1, 1.5f, Animation.RELATIVE_TO_SELF, 0.5f, 1, 0.5f);
        // 设置持续时间
        animation.setDuration(4000);
        // 设置动画结束之后的状态是否是动画的最终状态
        animation.setFillAfter(true);
        // 设置循环次数
        animation.setRepeatCount(0);
        // 设置动画结束后事件
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // 已登录，进入首页/选择词书
                if (ConfigData.getIsLogged()) {
                    List<UserConfig> userConfigs = LitePal.where("userId = ?", ConfigData.getSinaNumLogged() + "").find(UserConfig.class);
                    if (userConfigs.get(0).getCurrentBookId() == -1) {
                        Intent intent = new Intent(WelcomeActivity.this, ChooseWordDBActivity.class);
                        startActivity(intent);
                        finish();
                    } else if (userConfigs.get(0).getCurrentBookId() != -1 && userConfigs.get(0).getWordNeedReciteNum() == 0) {
                        Intent intent = new Intent(WelcomeActivity.this, ChangePlanActivity.class);
                        startActivity(intent);
                        finish();
                    } else {

                        Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
                // 未登录，进入登录页面
                else {
                    Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }


}
